<template>
  <div class="department-management">
    <Navbar />
    <!-- 新增加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loader"></div>
    </div>
    <!-- 修改模板判断条件 -->
    <div v-if="departments.length === 0" class="empty-state">
      <template v-if="restaurantId > 0">
        <p>{{ restaurantName }}尚未创建部门</p>
        <button @click="showCreateDepartmentDialog">立即创建</button>
      </template>

      <template v-else>
        <p>餐厅信息加载异常</p>
        <button @click="router.back()">返回列表</button>
      </template>
    </div>
    <main class="main-content">
      <div class="header-section">
        <h1 class="restaurant-title">餐厅详情 - {{ restaurantName }}</h1>
        <button
            class="primary-btn create-btn"
            @click="showCreateDepartmentDialog"
        >
          <span class="btn-icon">+</span> 创建部门
        </button>
      </div>

      <!-- 部门列表 -->
      <div class="department-list">
        <div v-if="departments.length === 0" class="empty-state">
          <!-- <img src="@/assets/empty-department.svg" alt="空状态" class="empty-img"> -->
          <p>尚未创建任何部门</p>
        </div>

        <table v-else class="styled-table">
          <thead>
          <tr>
            <th>部门名称</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="department in departments" :key="department.id">
            <td>{{ department.name }}</td>
            <td>
              <button
                  class="action-btn detail-btn"
                  @click="showDishManagement(department)"
              >
                详情
              </button>
              <button
                  class="action-btn edit-btn"
                  @click="handleEditDepartment(department)"
              >
                编辑
              </button>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <!-- 创建部门模态框 -->
      <div v-if="createDepartmentDialogVisible" class="modal-overlay">
        <div class="modal-container">
          <div class="modal-header">
            <h2>创建或者修改部门</h2>
            <button
                class="close-btn"
                @click="createDepartmentDialogVisible = false"
            >
              &times;
            </button>
          </div>

          <form @submit.prevent="handleCreateDepartment" class="department-form">
            <div class="form-group">
              <label for="departmentName">部门名称</label>
              <input
                  id="departmentName"
                  v-model="departmentForm.name"
                  type="text"
                  required
                  placeholder="请输入部门名称"
                  class="form-input"
                  @input="clearValidation"
              >
              <div v-if="validationError" class="error-message">
                {{ validationError }}
              </div>
            </div>

            <div class="form-actions">
              <button
                  type="button"
                  class="cancel-btn"
                  @click="createDepartmentDialogVisible = false"
              >
                取消
              </button>
              <button type="submit" class="submit-btn">
                创建部门
              </button>
            </div>
          </form>
        </div>
      </div>
    </main>
  </div>
  <DepartmentDishes
      v-if="showDishDialog"
      :restaurant-id="restaurantId"
      :department-id="selectedDepartment?.id"
      :department-name="selectedDepartment?.name"
      @close="showDishDialog = false"
  />
</template>

<script setup>
import Navbar from '../Common/Navbar.vue'
import { ref, reactive, onMounted } from 'vue'
import { getAllDepartments, addDepartment } from '@/api'
import {useRoute, useRouter} from 'vue-router'
import DepartmentDishes from "@/components/User/DepartmentDishes.vue";

// 从路由参数获取餐厅ID
const route = useRoute()
const router = useRouter()
const restaurantId = ref(Number(route.params.restaurantId))
const restaurantName = ref(route.query.name || '未知餐厅')

// 添加加载状态和缓存
const loading = ref(false)
const departmentCache = reactive({})

const departments = ref([])
const createDepartmentDialogVisible = ref(false)
const departmentForm = reactive({ name: '' })
const validationError = ref('')
const showDishDialog = ref(false)
const selectedDepartment = ref(null)

// 显示菜品管理
const showDishManagement = (department) => {
  selectedDepartment.value = department
  showDishDialog.value = true
}
// 表单验证
const validateForm = () => {
  if (!departmentForm.name.trim()) {
    validationError.value = '部门名称不能为空'
    return false
  }
  return true
}

// 清空验证信息
const clearValidation = () => {
  validationError.value = ''
}

// 优化后的获取部门方法
const fetchDepartments = async () => {
  try {
    loading.value = true

    // 缓存命中检查
    if (departmentCache[restaurantId.value]) {
      departments.value = departmentCache[restaurantId.value]
      return
    }

    const { data, success, message } = await getAllDepartments({
      restaurantId: restaurantId.value
    })

    if (success) {
      departments.value = data
      // 更新缓存
      departmentCache[restaurantId.value] = data
    } else {
      showMessage(message || '获取部门列表失败', 'error')
    }
  } catch (error) {
    console.error('请求异常:', error)
    showMessage(`网络错误: ${error.message}`, 'error')
  } finally {
    loading.value = false
  }
}

// 增强的创建部门方法
const handleCreateDepartment = async () => {
  if (!validateForm()) return

  try {
    const { success, message, data } = await addDepartment({
      ...departmentForm,
      restaurantId: restaurantId.value
    })

    if (success) {
      // 清除当前餐厅缓存
      delete departmentCache[restaurantId.value]
      await fetchDepartments()
      // 重置表单
      Object.assign(departmentForm, { name: '' })
      createDepartmentDialogVisible.value = false
      showMessage('部门创建成功', 'success')
    } else {
      showMessage(message || '创建失败', 'error')
    }
  } catch (error) {
    showMessage('网络请求异常，请检查连接', 'error')
  }
}
// 显示提示消息
const showMessage = (text, type) => {
  const msg = document.createElement('div')
  msg.className = `alert-message ${type}`
  msg.textContent = text
  document.body.appendChild(msg)
  setTimeout(() => msg.remove(), 3000)
}
// 在script setup区域补充缺失的方法
const showCreateDepartmentDialog = () => {
  if (restaurantId.value <= 0) {
    showMessage('请先选择有效餐厅', 'warning')
    return
  }
  validationError.value = ''
  createDepartmentDialogVisible.value = true
}
// 使用带类型校验的props
const props = defineProps({
  restaurantId: {
    type: Number,
    required: true
  }
})
const handleEditDepartment = (department) => {
  console.log('编辑部门:', department)
  // 根据实际需求实现编辑逻辑，示例：
  departmentForm.value = { ...department }
  createDepartmentDialogVisible.value = true
}
// 替换原有onMounted逻辑
onMounted(async () => {
  try {
    console.log('路由参数:', route.params)

    const id = Number(route.params.restaurantId)
    if (!id || id <= 0) throw new Error('无效餐厅ID')

    restaurantId.value = id
    restaurantName.value = route.query.name || '新餐厅'
    await fetchDepartments()
  } catch (error) {
    console.error('初始化失败:', error)
    showMessage(error.message, 'error')
    router.replace('/user/dashboard')
  }
})
</script>

<style scoped lang="scss">
.department-management {
  min-height: 100vh;
  background: #f8fafc;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.restaurant-title {
  font-size: 1.8rem;
  color: #1e293b;
  margin: 0;
}

.create-btn {
  background: #3b82f6;
  color: white;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;
  transition: transform 0.2s;

  &:hover {
    transform: translateY(-2px);
    background: #2563eb;
  }

  .btn-icon {
    margin-right: 0.5rem;
  }
}

.styled-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

  th, td {
    padding: 1rem;
    text-align: left;
  }

  th {
    background: #3b82f6;
    color: white;
    font-weight: 600;
  }

  tr:nth-child(even) {
    background: #f1f5f9;
  }
}

.action-btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.edit-btn {
  background: #10b981;
  color: white;

  &:hover {
    background: #059669;
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  padding: 2rem;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.department-form {
  .form-group {
    margin-bottom: 1.5rem;

    label {
      display: block;
      margin-bottom: 0.5rem;
      color: #374151;
      font-weight: 500;
    }
  }

  .form-input {
    width: 100%;
    padding: 0.75rem;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 1rem;
    transition: border-color 0.2s;

    &:focus {
      outline: none;
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
  }

  .error-message {
    color: #ef4444;
    font-size: 0.875rem;
    margin-top: 0.5rem;
  }
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}

.submit-btn {
  @extend .create-btn;
  padding: 0.75rem 1.5rem;
}

.cancel-btn {
  background: #f1f5f9;
  color: #64748b;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;

  &:hover {
    background: #e2e8f0;
  }
}

.empty-state {
  text-align: center;
  padding: 4rem 0;
  background: white;
  border-radius: 12px;

  .empty-img {
    width: 180px;
    margin-bottom: 1rem;
    opacity: 0.8;
  }

  p {
    color: #64748b;
    font-size: 1.125rem;
  }
}

@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }

  .styled-table {
    th, td {
      padding: 0.75rem;
    }
  }
}
.detail-btn {
  background: #3b82f6;
  color: white;
  margin-right: 0.5rem;
}
</style>